package com.elf.zero.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 指示器基类
 */
public abstract class AbsIndicator extends View {

    protected int mCount;
    protected int mItemWidth, mItemHeight, mItemSpace;
    protected int mNormalColor, mSelectedColor;
    protected int mSelectedIndex;
    protected Paint mPaint;

    public AbsIndicator(Context context) {
        this(context, null);
    }

    public AbsIndicator(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    protected void init() {
        mCount = 5;
        mItemWidth = 15;
        mItemHeight = 15;
        mItemSpace = 15;

        mNormalColor = Color.LTGRAY;
        mSelectedColor = Color.DKGRAY;

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }

    public void setCount(int value) {
        mCount = value;
        invalidate();
    }

    public void setItemSize(int width, int height, int space) {
        mItemWidth = width;
        mItemHeight = height;
        mItemSpace = space;
        invalidate();
    }

    public void setItemColor(int normalColor, int selectedColor) {
        mNormalColor = normalColor;
        mSelectedColor = selectedColor;
        invalidate();
    }

    public void setSelectedIndex(int value) {
        mSelectedIndex = value;
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = mItemWidth * mCount;
        if (mCount > 1) {
            width = width + (mCount - 1) * mItemSpace;
        }
        setMeasuredDimension(width, mItemHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int x = 0;
        for (int i = 0; i < mCount; i++) {

            if (mSelectedIndex == i) {
                mPaint.setColor(mSelectedColor);
            } else {
                mPaint.setColor(mNormalColor);
            }
            drawIndicator(canvas, x, mItemWidth, mItemHeight, mPaint);
            x += (mItemWidth + mItemSpace);
        }
    }

    protected abstract void drawIndicator(Canvas canvas, int x, int width, int height, Paint paint);
}
